<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button type="primary" :icon="Plus" @click="showTrademarkDialog">添加</el-button>
      </div>
    </template>
    <!-- data属性表示表格的数据源 border是让表格有竖线 -->
    <!-- label是表格的名称 -->
    <!-- prop是当前咧要显示的数据所对应的属性 -->
    <el-table  :data="tradmarkList"  border  style="width: 100%; margin-bottom: 20px"  v-loading="loading">
      <el-table-column type="index"  align="center"    label="序号"  width="80"/>
      <el-table-column  align="center"  prop="tmName"  label="品牌名称"  width="180" />
      <el-table-column align="center" label="品牌logo">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 100px" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template v-slot="{row}">
          <el-button title="编辑品牌" type="warning" :icon="Edit" size="small" @click="editTrademark(row)"/>
          <el-button title="删除品牌" type="danger" :icon="Delete" size="small" @click="delTradmark(row)"/>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout=" prev, pager, next, jumper, ->,sizes,total"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 添加品牌弹出框显示 -->
  <el-dialog v-model="dialogFormVisible" :title="`${tradmark.id ? '更新':'添加'}品牌`">
    <el-form ref="trademarkForm" :model="tradmark" :rules="rules">
      <el-form-item label="品牌名称" :label-width="formLabelWidth" prop="tmName" >
        <el-input v-model="tradmark.tmName" autocomplete="off" style="width:70%"/>
      </el-form-item>
      <el-form-item prop="logoUrl" label="品牌logo" :label-width="formLabelWidth">
         <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
          <img v-if="tradmark.logoUrl" :src="tradmark.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png文件,且不超过2M
            </div>
          </template>
          </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(trademarkForm)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "Tradmark",
};
</script>

<script setup lang="ts">
import { Plus,Edit,Delete } from "@element-plus/icons-vue";
import {reactive, ref, onMounted } from "vue";
import { reqDeleteTradmarkInfo, reqGetTradmarkInfoData ,reqSaveTrademarkInfo, reqUpdateTrademarkInfo} from "@/api/product/tradmark";
import type {TradmarkListModel, TradmarkModel} from "@/api/product/model/tradmarkModel"
import {ElMessage, ElMessageBox } from 'element-plus'
import type {UploadProps,FormInstance, FormRules} from 'element-plus'
// 表格   //不能用reactive，这里要完全赋值，会覆盖响应式。使用ref来定义响应式，value，会保留响应式
const tradmarkList = ref<TradmarkListModel>([]); 
// 分页器
const currentPage = ref(1);
const pageSize = ref(3);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const total = ref<number>(0);
// 加载
const loading = ref(true)
//弹出的对话框
const dialogFormVisible = ref(false)
const formLabelWidth = '90px'
 //图片上传的数据
const imageUrl=ref('')  
const BASE_URL = import.meta.env.VITE_API_URL

// 定义一个初始化Tradmark的函数，用于初始化数据
const initTrademark=()=> ({ logoUrl:'', tmName:''})
// const tradmark = reactive({
//  logoUrl:'',  //图片链接
//  tmName:''  //品牌名称
// })
const tradmark = reactive<TradmarkModel>(initTrademark())
//校验弹框
const trademarkForm =ref<FormInstance>()   
const rules = reactive<FormRules>({
   tmName: [
    { required: true, message: '品牌名称不能为空，请重新输入', trigger: 'blur' },
    { min: 3, max: 7, message: '长度应该在3到7之间，请重新输入', trigger: 'blur' },
  ],
  logoUrl:[
    {
      required:true,
      message:'请上传一张图片',
      trigger:'change'
    }
  ]
}) 

// 1.定义一个获取品牌数据的函数
const getTradmarkInfoData = async () => {
  const result = await reqGetTradmarkInfoData(currentPage.value,pageSize.value);
   ElMessage.success('获取品牌数据成功了...')
  // console.log("trade", result);
  tradmarkList.value = result.records;
  total.value = result.total;
  //关闭loading效果
  loading.value =false

};
// 2.当页面组件挂载完毕之后获取数据
onMounted(() => {
  getTradmarkInfoData();
});

// 3.每页显示的数量
const handleSizeChange = (val: number) => {
  console.log(`page: ${val}`);
  pageSize.value = val
  currentPage.value = 1
  getTradmarkInfoData()
};
// 4.单击页码时，改变页码
const handleCurrentChange = (val: number) => {
  console.log(`currentPage:${val}`);
  currentPage.value = val
  // 重新发送请求，获取渲染页面
  getTradmarkInfoData()
};

// 5.图片上传成功会触发的函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
 console.log('uu',uploadFile.raw);
 imageUrl.value = URL.createObjectURL(uploadFile.raw!)
//  将图片在服务器地址保存一下
tradmark.logoUrl = response.data
}

// 6.上传前需要做校验图片大小格式等的函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const imgTypes = ['image/jpeg','image/png','image/webp']
  if (!imgTypes.includes(rawFile.type)) {
    ElMessage.error('图片格式不正确，请重新选择')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小应该小于2M，请重新选择')
    return false
  }
  return true
}
// 7.单击添加按钮，弹出对话框
const showTrademarkDialog =()=>{
  //清空弹框的内容
  Object.assign(tradmark,initTrademark())   
  // 删除id,防止污染添加的数据。编辑之后取消再添加的时候不删除id会影响添加数据的id
  delete tradmark.id
  //弹出对话框
  dialogFormVisible.value = true
  // 清空表单校验提示
  trademarkForm.value?.clearValidate()
}

// 8.实现添加品牌数据
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async(valid, fields) => {
    console.log('vv',fields);
    if (valid) {
        if(tradmark.id){
        await reqUpdateTrademarkInfo(tradmark)
      }else{
        await reqSaveTrademarkInfo(tradmark)
        // 添加成功后最好调到第一页，有助于查看新的内容
        currentPage.value = 1
      }
      ElMessage({
        type:'success',
        message:'操作品牌成功'
      })
      dialogFormVisible.value = false
      getTradmarkInfoData()
    } else {
      console.log('error submit!', fields)
    }
  })
}
// const btnTrademark =async ()=>{
//   // 成功之后才会继续向下执行
//   if(tradmark.id){
//     await reqUpdateTrademarkInfo(tradmark)
//   }else{
//     await reqSaveTrademarkInfo(tradmark)
//     // 添加成功后最好调到第一页，有助于查看新的内容
//     currentPage.value = 1
//   }
//   ElMessage({
//     type:'success',
//     message:'操作品牌成功'
//   })
//   dialogFormVisible.value = false
//   getTradmarkInfoData()
// }
// 9.删除品牌
const delTradmark = (row:TradmarkModel)=>{
  ElMessageBox.confirm(
    `您真的要删除${row.tmName}品牌吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await reqDeleteTradmarkInfo(row.id as number)
      ElMessage({
        type: 'success',
        message: '删除当前品牌成功',
      })
      // 重新刷新一下页面,重新请求
      getTradmarkInfoData()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除了',
      })
    })
}
  // 10.（1）更新品牌之编辑数据回显
  const editTrademark = (row:TradmarkModel)=>{
  // 10.1将待编辑的数据要显示出来，也就是给tardmark赋值
  Object.assign(tradmark,row)
  // 10 （2）弹出对话框
  dialogFormVisible.value = true
}
// 11 更新品牌值确定更新，更新品牌的确定按钮和添加是一个逻辑代码在添加品牌处完成
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>